<template>
	<view class="container">
		<view class="container-content">
			<view class="room-top-container">
				<view class="room-top-container-time">
					<view class="context-time">
						<view>{{ submitObj.CheckInDate | formatDate }}</view>
						<view class="middle-text">至</view>
						<view>{{ submitObj.CheckOutDate | formatDate }}</view>
					</view>
					<view class="context-time-number">
						<view>共{{ submitObj.CheckInDays }}晚</view>
					</view>
				</view>
				<view class="room-type-name">{{ submitObj.RoomTypeName }}</view>
			</view>

			<view class="select-protocol">
				<checkbox :checked="isAgree" @click="clickCheckbox(isAgree)" />
				<text style="margin-left:16rpx ;">我已同意</text>
				<text class="select-protocol-link" @click="handleService">《用户服务协议》及《隐私政策》</text>
			</view>
			<view class="customer-card">
				<view class="customer-card-title">预约信息</view>
				<view class="customer-card-item" style="border-top: unset;">
					<view class="title">客户姓名</view>
					<input maxlength="20" class="form-container-item_textarea" type="text"
						v-model="submitObj.CustomerName" placeholder="请输入客户姓名" />
				</view>
				<view class="customer-card-item">
					<view class="title">联系电话</view>
					<input maxlength="11" class="form-container-item_textarea" type="text"  onkeyup="value=(value.replace(/\D/g,'')==''?'':parseInt(value))"
						v-model="submitObj.CustomerPhoneNumber" placeholder="请输入联系电话" />
				</view>
				<view class="customer-card-item">
					<view class="title">身份证号</view>
					<input maxlength="18" class="form-container-item_textarea" type="text"
						v-model="submitObj.CustomerIdentity" placeholder="请输入身份证号" />
				</view>
				<view class="customer-card-item">
					<view class="title">预计到店</view>
					<view class="form-container-item_textarea arrival-time" v-if="loadingBeforeDataStatus">
						<timeSelector showType="time" @btnConfirm="bindArrivalTimeChange"
							:beginDate="submitObj.CheckInDate" :endDate="submitObj.CheckOutDate">
							<view v-if="submitObj.ArrivalTime" class="uni-input">{{ submitObj.ArrivalTime }}</view>
							<view v-else class="tips-text">请选择预计到店时间</view>
						</timeSelector>
						<image class="context-time-number-image" src="../../static/images/right.png"></image>
					</view>
				</view>
				<view class="customer-card-item">
					<view class="title">推荐人</view>
					<input maxlength="20" class="form-container-item_textarea" type="text" v-model="submitObj.Remark"
						placeholder="请输入推荐人(可为空)" />
				</view>
				<!-- <view class="customer-card-item">
					<view class="title">优惠券</view>
					<view class="form-container-item_textarea arrival-time">
						<text class="tips-text" @click="choosecoupon">点击选择优惠券</text>
						<image class="context-time-number-image" src="../../static/images/right.png"></image>
					</view>
				</view> -->
			</view>
			<view class="price-card">
				<view class="price-title">
					<view>
						费用明细
						<text v-if="isVip" class="vip-tip-text"
							style="margin-left: 10rpx;">{{ submitObj.VipGuestRoomDiscountInfo.DiscountString }}</text>
					</view>
				</view>

				<view class="price-detail-card">
					<view class="detail-card-title-left">在线支付</view>

					<view class="detail-card-title-right">
						<text style="margin-right: 10rpx;">共{{ submitObj.CheckInDays }}晚</text>
						<span>
							共
							<text style="color: #FE7904;">{{ submitObj.TotalAmount | formatMoneyRmbUnit }}</text>
						</span>
					</view>
				</view>
				<view>
					<view class="price-detail-table-header">
						<view>房费</view>
						<view>{{ submitObj.TotalAmount | formatMoneyRmbUnit }}</view>
					</view>
					<view class="price-detail-table-tr" v-for="(item, index) in selectDetailPriceList" :key="index">
						<view>{{ item.date }}</view>
						<view>{{ item.price | formatMoneyRmbUnit }}</view>
					</view>
					<!-- <view class="price-detail-table-header">
						<view>优惠券</view>
						<view style="color: #FE7904;">-{{ submitObj.PreferentialPrice | formatMoneyRmbUnit }}</view>
					</view> -->
				</view>
			</view>
			<view class="config-card" v-if="xyStoreRoomRefundConfig.length > 0">
				<view class="config-card-item" v-for="(item, index) in xyStoreRoomRefundConfig" :key="index">
					<view class="config-title">{{ item.Title }}</view>
					<view class="config-content" v-html="item.ContentDetail"></view>
				</view>
			</view>
		</view>
		<view class="room-bottom-operation">
			<view class="room-bottom-container">
				<view class="room-right">
					<view class="price">{{ submitObj.TotalAmount - submitObj.PreferentialPrice | formatMoneyRmbUnit }}
					</view>
					<view v-if="isVip" class="vip-tip-text">{{ submitObj.VipGuestRoomDiscountInfo.DiscountString }}
					</view>
				</view>
				<button @click="$noMultipleClicks(submitGuestRoomOrder)" :disabled="submitStatus"
					:loading="submitStatus" class="submit-btn">提交订单</button>
			</view>
		</view>
		<uni-popup ref="popup" type="bottom">
			<customer-coupon :customerCouponList="customerCouponList" :totalMoney="totalMoney" @cancelBtn="cancelBtn"
				@confirmSelectedCoupon="confirmSelectedCoupon" @clickCouponItem="clickCouponItem"></customer-coupon>
		</uni-popup>
	</view>
</template>

<script>
	import {
		isLogin,
		toLogin,
		formatTime,
		successToShow,
		errorToShow,
		formatDate,
		getAddDateStr,
		formatDateToChinese,
		isPhoneNumber,
		isIdentity
	} from '@/config/common.js';
	import {
		getCurrentLocation,
		subStringLength
	} from '@/config/utils.js';
	import {
		getXyStoreGuestRoomPrice,
		submitXyGuestRoom,
		getGuestRoomCoupons,
		searchAllXyStoreRoomExplain
	} from '@/constant/xyGuestRoom.js';
	import timeSelector from '@/components/wing-time-selector/wing-time-selector.vue';

	import uniPopup from '@/components/uni-popup/uni-popup.vue';

	import customerCoupon from '@/packagePages/player/placeorder/customerCoupon/index.vue';
	export default {
		components: {
			timeSelector,
			customerCoupon
		},
		data() {
			return {
				isAgree: false,
				submitStatus: false,
				isVip: false,
				selectDetailPriceList: [],
				xyStoreRoomRefundConfig: [],
				loadingBeforeDataStatus: false,
				customerCouponList: [],
				requestCustomerCouponList: [],
				couponSettingList: [],
				submitObj: {
					CustomerId: uni.getStorageSync('customerId'),
					CheckInDays: '',
					CheckInDate: '',
					CheckOutDate: '',
					RoomTypeId: '',
					RoomTypeName: '',
					RoomTypeImg: '',
					XingYunStoreAlias: '',
					XingYunStoreName: '',
					RoomTypeInfo: {},
					CustomerName: '',
					CustomerIdentity: '',
					CustomerPhoneNumber: '',
					TotalAmount: 0,
					PreferentialPrice: 0,
					RealPrice: 0,
					Remark: '',
					ArrivalTime: '',
					CustomerCouponIds: [],
					VipGuestRoomDiscountInfo: {
						VipLevelInfo: {
							LevelName: ''
						}
					}
				}
			};
		},
		onLoad: function(option) {
			// this.searchAllXyStoreRoomExplain();
			this.initGuestOrderFilter(option);
		},
		filters: {
			formatDate: function(value) {
				return formatDateToChinese(value);
			}
		},
		methods: {
			initGuestOrderFilter(option) {
				if (!option.guestRoomOrder) {
					errorToShow('获取参数出错');
					return;
				}
				let guestRoomOrder = JSON.parse(decodeURIComponent(option.guestRoomOrder));
				console.log(guestRoomOrder, 'guestRoomOrder----')
				this.submitObj.CheckInDays = guestRoomOrder.CheckInDays;
				this.submitObj.CheckInDate = guestRoomOrder.CheckInDate;
				this.submitObj.CheckOutDate = guestRoomOrder.CheckOutDate;
				this.submitObj.RoomTypeId = guestRoomOrder.RoomTypeId;
				this.submitObj.RoomTypeName = guestRoomOrder.RoomTypeName;
				this.submitObj.RoomTypeImg = guestRoomOrder.RoomTypeInfo.img;
				this.submitObj.XingYunStoreAlias = guestRoomOrder.XingYunStoreAlias;
				this.submitObj.XingYunStoreName = guestRoomOrder.XingYunStoreName;
				this.submitObj.RoomTypeInfo = guestRoomOrder.RoomTypeInfo;
				// this.submitObj.ArrivalTime = guestRoomOrder.CheckInDate + ' 15:00';
				this.loadingBeforeDataStatus = true;
				uni.setNavigationBarTitle({
					title: this.submitObj.XingYunStoreName
				});
				let dateBetweenResult = this.getDayAll(this.submitObj.CheckInDate, this.submitObj.CheckOutDate);

				let price = guestRoomOrder.RoomTypeInfo.price
				this.submitObj.TotalAmount = price * this.submitObj.CheckInDays
				// this.getXyStoreGuestRoomPrice(dateBetweenResult.splice(0, dateBetweenResult.length - 1));
			},
			clickCheckbox(e) {
				this.isAgree = !e;
			},
			handleService: function() {
				uni.navigateTo({
					url: './xyRoomDetail/service-terms'
				});
			},
			getDayAll(starDay, endDay) {
				let arr = [];
				let dates = [];
				// 设置两个日期UTC时间
				let db = new Date(starDay);
				let de = new Date(endDay);
				// 获取两个日期GTM时间
				let s = db.getTime() - 24 * 60 * 60 * 1000;
				let d = de.getTime() - 24 * 60 * 60 * 1000;
				// 获取到两个日期之间的每一天的毫秒数
				for (let i = s; i <= d;) {
					i = i + 24 * 60 * 60 * 1000;
					arr.push(parseInt(i));
				}
				// 获取每一天的时间  YY-MM-DD
				for (let j in arr) {
					let time = new Date(arr[j]);
					let year = time.getFullYear(time);
					let mouth = time.getMonth() + 1 >= 10 ? time.getMonth() + 1 : '0' + (time.getMonth() + 1);
					let day = time.getDate() >= 10 ? time.getDate() : '0' + time.getDate();
					let YYMMDD = year + '-' + mouth + '-' + day;
					dates.push(YYMMDD);
				}
				return dates;
			},
			async getXyStoreGuestRoomPrice(selectDateList) {
				try {
					let result = await getXyStoreGuestRoomPrice(this.submitObj);
					this.isVip = result.VipGuestRoomDiscountInfo != null;
					this.submitObj.CustomerName = result.CustomerInfo.UserName;
					this.submitObj.CustomerIdentity = result.CustomerInfo.Identity;
					this.submitObj.CustomerPhoneNumber = result.CustomerInfo.Phone;
					this.submitObj.TotalAmount = result.TotalAmount;
					this.submitObj.RealPrice = result.TotalAmount;
					this.submitObj.PreferentialPrice = 0;

					if (result.VipGuestRoomDiscountInfo != null) {
						this.submitObj.VipGuestRoomDiscountInfo = result.VipGuestRoomDiscountInfo;
					}
					this.initGuestRoomDetailPrice(selectDateList, result.XyEveryDayPriceList);
				} catch (e) {
					setTimeout(function() {
						uni.navigateBack();
					}, 1000);
				}
			},
			initGuestRoomDetailPrice(selectDateList, everyPriceList) {
				this.selectDetailPriceList = [];
				for (let i = 0, length = selectDateList.length; i < length; i++) {
					let itemPrice = {
						date: selectDateList[i],
						price: everyPriceList[i]
					};
					this.selectDetailPriceList.push(itemPrice);
				}
			},
			bindArrivalTimeChange(e) {
				this.submitObj.ArrivalTime = e.key;
			},
			async choosecoupon() {
				let result = await this.getGuestRoomCoupons();
				if (!result) {
					return;
				}

				this.$refs.popup.open();
			},
			cancelBtn() {
				this.$refs.popup.close();
			},
			async getGuestRoomCoupons() {
				this.customerCouponList = await getGuestRoomCoupons({
					TotalAmount: this.submitObj.TotalAmount
				});
				if (this.customerCouponList.length == 0) {
					errorToShow('无可用优惠券');
					return false;
				}
				if (this.submitObj.CustomerCouponIds.length > 0) {
					this.submitObj.CustomerCouponIds.forEach(r => {
						let couponItem = this.customerCouponList.find(item => item.Id == r);
						if (couponItem) {
							couponItem.IsActive = true;
						}
					});
				}
				this.requestCustomerCouponList = [];
				this.customerCouponList.forEach(item => {
					this.requestCustomerCouponList.push(item);
				});
				return true;
			},
			clickCouponItem(item) {
				this.customerCouponList = [];
				let groupList = this.requestCustomerCouponList;
				this.requestCustomerCouponList.forEach(r => {
					if (r.Id == item.Id) {
						r.IsActive = !item.IsActive;
					}
					//单选
					if (r.Id != item.Id) {
						r.IsActive = false;
					}
					this.customerCouponList.push(r);
				});
				const selectedCouponList = groupList.filter(item => item.IsActive);
				let totalCouponAmount = selectedCouponList.reduce((total, item) => {
					return total + item.Amount;
				}, 0);
				const result = this.checkCouponAmount(totalCouponAmount);
				if (!result) {
					errorToShow('优惠券金额不能大于订单金额');
					this.changeCustomerCouponList(totalCouponAmount, item);
					return;
				}
			},
			changeCustomerCouponList(totalCouponAmount, item) {
				totalCouponAmount = totalCouponAmount - item.Amount;
				let _that = this;
				setTimeout(() => {
					_that.customerCouponList.find(r => r.Id == item.Id).IsActive = false;
				}, 200);
			},
			checkCouponAmount(totalCouponAmount) {
				const totalAmount = this.totalMoney;
				if (totalCouponAmount >= totalAmount) {
					return false;
				}
				return true;
			},
			confirmSelectedCoupon(selectedCouponList) {
				this.submitObj.PreferentialPrice = selectedCouponList.reduce((total, item) => {
					return total + item.Amount;
				}, 0);
				this.submitObj.CustomerCouponIds = [];
				selectedCouponList.forEach(item => {
					this.submitObj.CustomerCouponIds.push(item.Id);
				});
				this.cancelBtn();
			},

			verityForm() {
				if (!this.submitObj.CustomerName) {
					errorToShow('请输入客户姓名');
					return false;
				}
				if (!this.submitObj.CustomerPhoneNumber) {
					errorToShow('请输入联系电话');
					return false;
				}
				if (!isPhoneNumber(this.submitObj.CustomerPhoneNumber)) {
					errorToShow('联系电话格式不正确');
					return false;
				}
				if (!this.submitObj.CustomerIdentity) {
					errorToShow('请输入身份证号');
					return false;
				}
				if (!isIdentity(this.submitObj.CustomerIdentity)) {
					errorToShow('身份证格式不正确');
					return false;
				}
				if (!this.submitObj.ArrivalTime) {
					errorToShow('请选择预计到店时间');
					return false;
				}
				if (!this.isAgree) {
					uni.showToast({
						icon: 'none',
						title: '请先同意协议'
					});
					return;
				}
				return true;
			},
			async searchAllXyStoreRoomExplain() {
				this.xyStoreRoomRefundConfig = [];
				let result = await searchAllXyStoreRoomExplain();
				result.forEach(item => {
					if (item.ContentDetail) {
						item.ContentDetail = item.ContentDetail.replace(/style=""/gi,
							'style="max-width:100%;" ');
						item.ContentDetail = item.ContentDetail.replace(/\<img/gi,
							'<img style="max-width:100%;" ');
						this.xyStoreRoomRefundConfig.push({
							Title: item.Title,
							ContentDetail: item.ContentDetail
						});
					}
				});
			},
			async submitGuestRoomOrder() {
				console.log(this.verityForm(),'this.verityForm()')
				if (!this.verityForm()) {
					return;
				}
				
					if (this.submitObj.TotalAmount <= 0) {
						errorToShow('支付金额不能小于等于0');
						return false;
					}
						console.log(this.submitObj.TotalAmount,'this.submitObj.TotalAmount')
					this.submitStatus = true;
					console.log(this.submitObj,'this.submitObj')
					console.log(this.submitObj.RoomTypeInfo,'this.submitObj.RoomTypeInfo')
					let params = {
						"storeId": this.submitObj.XingYunStoreAlias,
						"tableNumber": "",
						"checkInTime": this.submitObj.CheckInDate,
						"checkOutTime": this.submitObj.CheckOutDate,
						"roomTypeId": this.submitObj.RoomTypeId,
						"planInTime":this.submitObj.ArrivalTime+':00',
						"name": this.submitObj.XingYunStoreName,
						"phone": this.submitObj.CustomerPhoneNumber,
						"identy": this.submitObj.CustomerIdentity,
						storeAlias:this.submitObj.XingYunStoreAlias,
						storeName:this.submitObj.XingYunStoreName,
						storeAddress:this.submitObj.XingYunAddress,
						roomTypeName:this.submitObj.RoomTypeInfo.name,
						roomTypeImg:this.submitObj.RoomTypeInfo.img,
						
					}
					console.log(params,'params')
					let result = await submitXyGuestRoom(params);
					console.log(result,'result')
					this.submitStatus = false;
					if (result) {
						successToShow('订单提交成功', res => {
							uni.reLaunch({
								url: '/pages/payorder/index?orderNo=' + result.data.orderNo + '&orderAmount=' + result.data.realPrice
							});
						});
					}
				
			}
		}
	};
</script>
<style>
	button::after {
		border: unset;
	}
</style>

<style scoped lang="scss">
	.container {
		background-color: #f5f6fd;
		height: 100vh;
		overflow-x: hidden;
		overflow-y: hidden;
	}

	.container-content {
		overflow-y: auto;
		height: calc(100vh - 130rpx);
	}

	.room-top-container {
		padding: 30rpx;
		background-color: #ffffff;
		margin-bottom: 20rpx;
		font-size: $main-text-size-28;
		font-weight: 600;

		.room-top-container-time {
			display: flex;
			justify-content: space-between;

			.context-time {
				display: flex;

				.middle-text {
					margin-left: 12rpx;
					margin-right: 12rpx;
				}
			}
		}

		.room-type-name {
			// font-size: $main-text-size-28;
			// font-weight: bold;
		}
	}

	.form-container-item_textarea {
		text-align: right;
		width: 480rpx;
		font-size: $main-text-size-28;
		color: $main-text-color-gray-33;
	}

	.context-time-number-image {
		width: 15rpx;
		height: 27rpx;
		margin-left: 10rpx;

		image {
			width: 100%;
			height: 100%;
		}
	}

	.arrival-time {
		display: flex;
		justify-content: flex-end;
		align-items: center;

		.uni-input {
			display: contents;
		}

		.tips-text {
			font-size: $main-text-size-28;
			color: $main-text-color-grey;
		}
	}

	.room-bottom-operation {
		height: 130rpx;
		position: absolute;
		background-color: #ffffff;
		width: 100%;
		bottom: 0;
		box-shadow: 0px -1rpx 2rpx rgba(68, 68, 68, 0.16);

		.room-bottom-container {
			display: flex;
			justify-content: space-between;
			padding: 30rpx;
			align-items: center;

			.submit-btn {
				color: #fff;
				font-size: 32rpx;
				margin-right: 0rpx;
				text-align: center;
				background-color: #f7772a;
			}

			.room-right {
				.price {
					color: $main-text-color-main-orange;
					font-size: $main-text-size-40;
				}
			}
		}
	}

	.vip-tip-text {
		font-size: 20rpx;
		color: $main-text-color-orange-FCC309;
	}

	.customer-card :first-child {
		border-top: unset;
	}

	.customer-card {
		padding: 10rpx 30rpx;
		background-color: #ffffff;
		margin-bottom: 20rpx;

		&-title {
			color: $main-text-color-gray-33;
			font-size: $main-text-size-28;
			margin-top: 20rpx;
			font-weight: 600;
			margin-bottom: 20rpx;
		}

		&-item {
			display: flex;
			justify-content: space-between;
			min-height: 80rpx;
			align-items: center;
			margin-bottom: 10rpx;
			position: relative;
			border-top: 2rpx solid #f1f1f1;

			.title {
				color: $main-text-color-gray-black;
				font-size: $main-text-size-28;
			}
		}
	}

	.price-card {
		padding: 10rpx 30rpx;
		background-color: #ffffff;
		margin-bottom: 20rpx;

		.price-title {
			margin-top: 20rpx;
			font-size: $main-text-size-28;
			color: $main-text-color-gray-33;
			font-weight: 600;
			margin-bottom: 20rpx;
		}

		.price-detail-card {
			display: flex;
			justify-content: space-between;
			font-size: $main-text-size-26;
			padding-bottom: 24rpx;
			border-bottom: 2rpx solid #f1f1f1;
			font-weight: 600;
			color: $main-text-color-gray-33;
		}

		.price-detail-table-header {
			font-size: $main-text-size-26;
			display: flex;
			justify-content: space-between;
			font-weight: 600;
			margin-top: 24rpx;
			margin-bottom: 24rpx;
			color: $main-text-color-gray-33;
		}

		.price-detail-table-tr {
			display: flex;
			justify-content: space-between;
			margin-bottom: 24rpx;
			font-size: $main-text-size-24;
			color: $main-text-color-gray-black;
		}
	}

	.config-card {
		padding: 10rpx 30rpx;
		background-color: #ffffff;
		margin-bottom: 20rpx;

		&-item {
			margin-bottom: 40rpx;

			.config-title {
				margin-top: 20rpx;
				font-size: $main-text-size-28;
				color: $main-text-color-gray-33;
				font-weight: 600;
				margin-bottom: 16rpx;
			}

			.config-content {
				font-size: $main-text-size-24;
				color: $main-text-color-gray-black;
			}
		}
	}

	.select-protocol {
		font-size: $main-text-size-32;
		margin-top: 0px;
		padding-left: 30rpx;
		color: $main-text-color-gray-33;
		display: flex;
		align-items: center;

		&-link {
			color: #68c8ff;
		}
	}
</style>